package com.cjk.foundation.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class XmlUtil {
	
	public static String mapToXmlString(Map<String, Object> map){
		StringBuffer buffer = new StringBuffer("<xml>");
		for(String key : map.keySet()){
			String append = String.format("<%s>%s</%s>", key, map.get(key), key);
			buffer.append(append);
		}
		buffer.append("</xml>");
		return buffer.toString();
	}
	
	@SuppressWarnings("unchecked")
	public static Map<String, String> xmlStringToMap(String xml) {
		Map<String, String> rRts = new HashMap<String, String>();
		Document document = null;
		try {
			document = DocumentHelper.parseText(xml);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		Element root = document.getRootElement();
		List<Element> list = root.elements();
		for (int i = 0; i < list.size(); i++) {
			Element item = (Element) list.get(i);
			rRts.put(item.getName(), item.getText());
		}
		return rRts;
	}
	
}
